package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.math.BigDecimal;

/**
 * 用户余额控制器
 */
@RestController
@RequestMapping("/balance")
public class UserBalanceController {

    private static final Logger log = LoggerFactory.getLogger(UserBalanceController.class);

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户的余额信息
     * @return 余额信息
     */
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserBalance() {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }

            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            String phone = user.getPhone();
            log.info("获取当前登录用户的余额信息，用户ID: {}, 手机号: {}", userId, phone);

            // 获取用户余额
            UserBalance userBalance = userBalanceService.getUserBalance(phone);

            Map<String, Object> data = new HashMap<>();
            if (userBalance != null) {
                data.put("vipLevel", userBalance.getVipLevel());
                data.put("vipExpireTime", userBalance.getVipExpireTime());
                data.put("exportQuotaRemaining", userBalance.getExportQuotaRemaining());
                data.put("viewRecordsRemaining", userBalance.getViewRecordsRemaining());
                data.put("reverseLookupRemaining", userBalance.getReverseLookupRemaining());
                data.put("emailSendRemaining", userBalance.getEmailSendRemaining());
            } else {
                log.warn("未找到用户{}的余额信息", phone);
                data.put("vipLevel", 0);
                data.put("vipExpireTime", null);
                data.put("exportQuotaRemaining", 0);
                data.put("viewRecordsRemaining", 5); // 免费用户默认5次
                data.put("reverseLookupRemaining", 0);
                data.put("emailSendRemaining", 0);
            }

            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户余额信息失败: {}", e.getMessage(), e);
            return Result.error("获取用户余额信息失败: " + e.getMessage());
        }
    }

    /**
     * 同步用户余额信息（确保当前登录用户在user_balances表中有记录）
     * @return 同步结果
     */
    @PostMapping("/sync")
    public Result<Boolean> syncUserBalance() {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }

            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            String phone = user.getPhone();
            log.info("同步当前登录用户的余额信息，用户ID: {}, 手机号: {}", userId, phone);

            // 获取用户余额
            UserBalance userBalance = userBalanceService.getUserBalance(phone);
            if (userBalance == null) {
                // 如果用户没有余额记录，创建一个默认的免费版记录
                boolean result = userBalanceService.updateUserVip(phone, 0, 0, 0, 0, 0);
                return Result.success(result, result ? "同步成功" : "同步失败");
            }

            return Result.success(true, "用户余额记录已存在，无需同步");
        } catch (Exception e) {
            log.error("同步用户余额信息时发生异常: {}", e.getMessage(), e);
            return Result.error("同步余额信息失败: " + e.getMessage());
        }
    }
} 